package com.xm.dao.impl;

import com.xm.dao.UserAddressDao;
import com.xm.po.UserAddress;
import com.xm.util.BaseDao;
import com.xm.util.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2020-08-07-15:37
 * @description 用户收货地址数据操作接口实现
 */
public class UserAddressDaoImpl implements UserAddressDao {
    /**
     * 新增收货地址
     * @param userAddress
     * @return
     */
    @Override
    public boolean add(UserAddress userAddress) {
        return DButil.insert(userAddress);
    }

    @Override
    public List<UserAddress> getUserAddress(Integer userId) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<UserAddress> list = new ArrayList<>();
        String sql = "select * from userAddress where userId = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,userId);
            rs = ps.executeQuery();
            list = (List<UserAddress>) DButil.getRsData(UserAddress.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return list;
    }
    /**
     * 平台用户收货地址
     * @return
     */
    @Override
    public List<UserAddress> list() {
        List<UserAddress>list= (List<UserAddress>) DButil.queryAll(UserAddress.class);
        return list;
    }
    /**
     * 删除指定收货地址
     * @param addressId
     * @return
     */
    @Override
    public boolean delete(String addressId) {
        return DButil.delete(UserAddress.class,addressId);
    }

    @Override
    public UserAddress getAddressById(Integer addressId) {
        return null;
    }

    @Override
    public boolean update(UserAddress userAddress) {
        return DButil.update(userAddress);
    }
    /**
     * 根据id查询用户地址
     * @param id
     * @return
     */
    @Override
    public UserAddress selectById(Integer id) {
        return (UserAddress) DButil.queryOne(UserAddress.class,id);
    }

    @Override
    public UserAddress getIsDefault(Integer userId) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        UserAddress userAddress = new UserAddress();
        String sql = "select * from userAddress where isDefault = 1 and userId = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,userId);
            rs = ps.executeQuery();
            userAddress = (UserAddress) DButil.getRsOne(UserAddress.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return userAddress;
    }
}
